<?php

namespace yunj\app\admin\enum;

use yunj\core\Model;
use think\facade\Db;
use yunj\core\response\Json;
use yunj\core\exception\ResponseJsonException;

final class TableBuilderEvent extends Enum {

    // 恢复正常
    const NORMAL = 'normal';
    // 移入回收站
    const RECYLE_BIN = 'recyle_bin';
    // 永久删除
    const DELETED = 'deleted';
    // 排序
    const SORT = 'sort';

    /**
     * 所有枚举的属性值
     * @return array
     */
    public static function allEnumAttrs(): array {
        return [
            self::NORMAL => [
                'desc' => '恢复正常',
                'dbStateVal' => State::NORMAL,
                'dbAllowDataStateVal' => State::RECYLE_BIN,
            ],
            self::RECYLE_BIN => [
                'desc' => '移入回收站',
                'dbStateVal' => State::RECYLE_BIN,
                'dbAllowDataStateVal' => State::NORMAL,
            ],
            self::DELETED => [
                'desc' => '永久删除',
                'dbStateVal' => State::DELETED,
                'dbAllowDataStateVal' => State::RECYLE_BIN,
            ],
            self::SORT => [
                'desc' => '排序'
            ]
        ];
    }

    /**
     * 获取映射的数据库state值
     * @return mixed|null
     */
    public function getDbStateVal() {
        return $this->getAttr('dbStateVal');
    }

    /**
     * 获取映射的数据库允许操作的数据state值
     * @return mixed|null
     */
    public function getDbAllowDataStateVal() {
        return $this->getAttr('dbAllowDataStateVal');
    }

    /**
     * 是否为状态事件
     * @return bool
     */
    public function isStateEvent(): bool {
        return in_array($this->getValue(), [self::NORMAL, self::RECYLE_BIN, self::DELETED]);
    }

    /**
     * 获取表格构建器链式操作state的值
     * @param Model $model
     * @param mixed $event
     * @param array $ids
     * @param null $filter
     * @return Json|null
     */
    public static function handleEvent(Model $model, $event, array $ids, $filter = null) {
        if (!self::isValue($event, true)) return null;
        try {
            $eventObj = self::byValue($event);
            $eventVal = $eventObj->getValue();
            $currTime = time();
            if (in_array($eventVal, [self::NORMAL, self::RECYLE_BIN, self::DELETED])) {
                // 状态处理
                $data = [
                    'state' => $eventObj->getDbStateVal(),
                    'last_update_time' => time(),
                ];
                $where = [
                    ['state', '=', $eventObj->getDbAllowDataStateVal()],
                    [$model->getPk(), 'in', $ids]
                ];
                $modelFunParams = [$data, $where];
                if ($filter instanceof \Closure) $modelFunParams = $filter($eventObj, $ids, $modelFunParams);
                call_user_func_array([$model, 'change'], $modelFunParams);
                return success_json(['reload' => true]);
            } elseif ($event == self::SORT) {
                // 排序处理
                $data = [];
                $sort = 0;
                foreach ($ids as $id) {
                    $data[] = [
                        $model->getPk() => $id,
                        'sort' => $sort,
                        'last_update_time' => time(),
                    ];
                    $sort++;
                };
                $modelFunParams = [$data];
                if ($filter instanceof \Closure) $modelFunParams = $filter($eventObj, $ids, $modelFunParams);
                call_user_func_array([$model, 'batchChange'], $modelFunParams);
                return success_json();
            }
        } catch (ResponseJsonException $e) {
            return $e->getResponse();
        } catch (\Exception $e) {
            log_exception($e);
            return error_json('服务器内部异常');
        }
        return null;
    }

}